package com.heima.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.heima.annotaion.LogAnnotation;
import com.heima.domain.FansDetail;
import com.heima.domain.TextMessage;
import com.heima.manger.WeChatManger;
import com.heima.service.WeChatService;
import com.heima.utils.HttpRequestUtils;
import com.heima.utils.MessageUtil;
import com.heima.utils.WeixinMessageUtil;
import com.heima.utils.WxCheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController

public class WxCotroller {
    //微信公众验证消息
/*    开发者通过检验signature对请求进行校验（下面有校验方式）。
    若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，
    否则接入失败。加密/校验流程如下：

            1）将token、timestamp、nonce三个参数进行字典序排序 2）将三个参数字符串拼接成一个字符串进行sha1加密 3）
    开发者获得加密后的字符串可与signature对比，标识该请求来源于微信*/


    @Autowired

    private WeChatManger weChatManger;

    @Autowired
    private WeixinMessageUtil weixinMessageUtil;


    @GetMapping("/wx")
    @LogAnnotation(type = "0101")

    public String test(@RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("echostr") String echostr,
                       HttpServletRequest request) throws Exception {

        System.out.println("======>");

        String token = "123456";
        //排序
        String sortString = WxCheckUtils.sort(token, timestamp, nonce);
        //加密
        String myString = WxCheckUtils.sha1(sortString);
        //校验
        if (myString != null && myString != "" && myString.equals(signature)) {
            System.out.println("签名校验通过");
            //如果检验成功原样返回echostr，微信服务器接收到此输出，才会确认检验完成。
            return echostr;
        } else {
            System.out.println("签名校验失败");
            return "";
        }
    }

    @Autowired
    private WeChatService weChatService;
    //接收卫星推送消息
    @LogAnnotation(type = "0102")
    @PostMapping(value = "/wx", produces = "application/xml;charset=utf-8")
    public String handler(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //将微信推送过来xml事件，转换成map
        Map<String, String> map = weixinMessageUtil.parseXml(request);
        return weChatService.handerMessage(map);





    }



    /*回调方法*/
  /*  @RequestMapping(value = "/callBack",produces = "application/json;charset=utf-8")
    public String callBack(String code, Map<String,Object> map) {
        //1.通过code获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url = url.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
        String tokenInfoStr = HttpRequestUtils.httpGet(url);

        JSONObject tokenInfoObject = new JSONObject(tokenInfoStr);

        //2.通过access_token和openid获取用户信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        userInfoUrl = userInfoUrl.replace("ACCESS_TOKEN", tokenInfoObject.getString("access_token")).replace("OPENID", tokenInfoObject.getString("openid"));
        String userInfoStr = HttpRequestUtils.httpGet(userInfoUrl);
        map.put("token", tokenInfoStr);

        //转为JSON
        JSONObject user = new JSONObject(userInfoStr);

        ///*只获取openid并返回,openid是微信用户的唯一标识,userInfoStr里面有用户的全部信息
        String openid = user.getString("openid");
        map.put("openid", openid);

        ///*获取用户头像url
        String headimgurl = user.getString("headimgurl");
        map.put("headimgurl", headimgurl);

        /*获取用户昵称
        String nickname = user.getString("nickname");
        map.put("nickname", nickname);
        System.out.println("  /*获取用户昵称"+nickname);*/

        /*获取用户性别
        int sex = user.getInt("sex");
        map.put("sex", sex);

        /*获取用户国家
        String country = user.getString("country");
        map.put("country", country);

        /*获取用户省份
        String province = user.getString("province");
        map.put("province", province);

        /*获取用户城市
        String city = user.getString("city");
        map.put("city", city); */


    //获取微信关注总人数
    @GetMapping("/wx/getFans")
    public Map getFans() {
        Integer fans = weChatManger.getFans();
        HashMap<String, Integer> map = new HashMap<>();
        map.put("fans", fans);
        return map;

    }

    //获取粉丝的详情
    @GetMapping("/wx/fansDetail")
    public FansDetail fansDetail(String openId) {

        return weChatManger.fansDetail(openId);
    }
//autowire作用在方法上会自动执行该方法，如果有参数则自动去从ioc容器中获取同类型的对象
    @Autowired
    public void test(WeChatManger weChatManger) {
        System.out.println(weChatManger);
        System.out.println("自动执行方法？？？");
        //
    }


}
